// Copyright (c) 2024, lanlian and contributors
// For license information, please see license.txt

frappe.ui.form.on("EMS Fault Repair", {
	refresh(frm) {
        // 故障维修单下推验收结算单
        frm.add_custom_button(__('Make EMS Acceptance Settlement'), () => {
            frappe.model.open_mapped_doc({
                method: "ems.equipment_managerment_system.doctype.ems_fault_repair.ems_fault_repair.make_acceptance_settlement",
                frm: cur_frm,
                freeze_message: __("Creating Task ...")
            });
        });
        // 下推备件其他出库
        if (!frm.is_new() && frm.doc.docstatus === 1 ) {
			frm.add_custom_button(__("Make Stock Entry"), ()=> {
				if( frm.doc.parts_item) {
					frappe.db.get_list('Stock Entry', {filters: {remarks: frm.doc.name, docstatus: ['<', 2]}})
					.then(records => {	
						if (records.length === 0) {
                            frappe.call({
                                method: "ems.equipment_managerment_system.doctype.server_config.server_config.make_stock_entry",
                                args: {
                                    source_name: frm.doc.name,
                                    stock_entry_type: "Material Issue",
                                },
                                callback: function (r) {
                                    var doclist = frappe.model.sync(r.message);
                                    console.log(r.message)
                                    frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
                                },
                            });
						}
						else {frappe.msgprint(`已经生成出库, 单号:${records[0].name}`)}
					})
				}
				else { frappe.msgprint("没有备件消耗记录不能出库!") }
			}).addClass('btn-primary');
		};
	},
});

let make_stock_entry = function(opts) {
	// 纯JS的New Doc
	let new_doc = frappe.model.get_new_doc("Stock Entry");
	new_doc.supplier_number = opts.stock_entry_type;
    // new_doc.add_child('items', {
    //     s_warehouse: "EMS备件仓库 - HD",
    //     item_code: "EMS-润滑油32#",
    //     qty: 2
    // });

	frappe.set_route("Form", new_doc.doctype, new_doc.name);
}